import { createApp } from 'vue'
// import "@/api"
//引入自定义指令
import directives from "@/directives"
import App from './App.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import eventBus from "./utils/eventBus"
//引入路由

import router from "./router"

//引入pinia
import { createPinia } from "pinia"

//引入公共样式

import "./assets/styles/common.scss"

//引入持久化存储的插件
import piniaPluginPersistedState from "pinia-plugin-persistedstate"

//引入menuStore
import useMenus from './store/menus'

//引入面包屑store
import useBread from "@/store/breadCrumb"

//引入全局组件库

import uiComponents from "@/components/ui-components"

import 'element-plus/theme-chalk/dark/css-vars.css'

//将eventBus挂载到全局

let app = createApp(App)

app.config.globalProperties.$bus = eventBus

let pinia = createPinia();

//将持久化存储的插件添加到pinia里面
pinia.use(piniaPluginPersistedState)

app.use(uiComponents)

app.use(pinia)

app.use(router)

app.use(ElementPlus)
//使用自定义指令
app.use(directives)
//全局守卫

//前置守卫,可以不传递next,如果传递了next,必须调用next,否则路由不会加载组件
//一般业务中可以判断用户是否登录,如果没有登录,就跳转到登录页面
router.beforeEach(async (to, from) => {

    //判断本地是否存储token,如果存储了,那么就允许访问其他页面,如果没有登录
    //判断用户访问的是不是/login这个页面,如果是就通过,不是就返回到login

    let { token } = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {}

    if (!token) {
        //没有token就是没有登入
        //判断访问的是不是login页面
        if (to.path !== "/login") {
            //如果访问的不是login 那么会跳转到login
            return { path: "/login" }
        }
    } else {
        let useMenusStore = useMenus()

        //判断store是否已经获取了用户数据

        if (!useMenusStore.userRoutes.length) {
            //如果没有菜单数据就要发起请求,获取菜单数据
            await useMenusStore.getMenus()
            //目的是为了能够重新激活心动态添加的路由
            return {
                ...to
            }
        }

        // console.log(useMenusStore)

    }

    // return false
})
//后置守卫

router.afterEach((to, from) => {
    // console.log('----from', from.path)
    console.log('----to', to)
    //这段逻辑是防止页面切换到登入页面不更新菜单的问题
    if (from.path !== "/login" && from.path !== "/" && to.path == "/login") {
        localStorage.removeItem('user')
        location.reload()
    }
    let breadStore = useBread();
    // console.log(breadStore)
    breadStore.breadData.value = to.matched.slice(1)

    // console.log(breadStore.breadData)
})

app.mount('#app')
